/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.asseco.mio.codex.controllers;

import com.asseco.mio.BasicInfo;
import com.asseco.mio.UserInstitution;
import com.asseco.mio.WorkPosition;
import com.asseco.mio.search.UserSearch;
import com.asseco.persistence.service.HibernateUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.model.User;
import org.appfuse.service.GenericManager;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author gjoko.mitrovski
 */
@Controller
@RequestMapping("/disciplineproceduresearchform*")
public class DisciplineProcedureSearchController {

    private GenericManager<BasicInfo, String> basicInfoManager;

    @Autowired
    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
        this.basicInfoManager = basicInfoManager;
    }

    public List getWorkPosition(WorkPosition workPosition, User user) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        if (workPosition.getEmployment() == null) {
            workPosition.setEmployment(new BasicInfo());
        }
        String pamFirstName = "%" + workPosition.getEmployment().getFirstName() + "%";
        String pamLastName = "%" + workPosition.getEmployment().getLastName() + "%";
        String pamSocScrNo = "%" + workPosition.getEmployment().getSocScrNo() + "%";
        Query q = session.createQuery("from WorkPosition workPos inner join workPos.employment where workPos.position != 'null' and "
                + " workPos.institution in (:parameter) and ( "
                + "workPos.employment.firstName like '" + pamFirstName + "' and "
                + "workPos.employment.lastName like '" + pamLastName + "' and "
                + "workPos.employment.socScrNo like '" + pamSocScrNo + "') order by workPos.employment,workPos.startDate");

        UserInstitution ui = new UserInstitution();
      List instList = ui.getInstitutionsForUser(user);
        q.setParameterList("parameter", instList);

        List tempResult = q.list();
        List result = new ArrayList();
        List result1 = new ArrayList();
        for (int j = 0; j < tempResult.size(); j++) {
            Object[] object = (Object[]) tempResult.get(j);
            WorkPosition wps = (WorkPosition) object[0];
            BasicInfo basInfo = (BasicInfo) wps.getEmployment();
            result.add(wps);
            System.out.print(basInfo.getFirstName() + "*********");
            System.out.print(basInfo.getId() + "*********");
            System.out.println(wps.getStartDate());
        }
        session.getTransaction().commit();
        String uid = "null";                    // so sreka nadole :)
        Boolean status = false;
        Boolean checkTwoDifferentInARow = false;
        for (int i = 0; i < result.size(); i++) {
            WorkPosition element = (WorkPosition) result.get(i);
            if (!uid.equals(element.getEmployment().getId())) {
                if (checkTwoDifferentInARow) {
                    WorkPosition prevElement = (WorkPosition) result.get(i - 1);
                    if (status) {
                        result1.add(prevElement);
                    }
                }else{
                if (i != 0) {
                    WorkPosition prevElement = (WorkPosition) result.get(i - 1);

                    if (status) {
                        result1.add(prevElement);
                    }
                }
                }
                if (element.getDiscriminator().equals("1")) {
                    status = true;
                } else {
                    status = false;
                }

                checkTwoDifferentInARow = true;
            } else {
                checkTwoDifferentInARow = false;
                if (element.getDiscriminator().equals("1")) {
                    status = true;
                } else {
                    status = false;
                }


            }
            uid = element.getEmployment().getId();
        }
        if (!result.isEmpty()) {
            WorkPosition element = (WorkPosition) result.get(result.size() - 1);
            if (element.getDiscriminator().equals("1")) {
                result1.add(element);
            }
        }
        return result1;


    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
 public ModelAndView doSubmit(WorkPosition workPosition, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
           String userString = request.getRemoteUser();
      User user = UserSearch.getUserByUserName(userString);

        return new ModelAndView("disciplineproceduresearchform", "disciplineproceduresearchformList", getWorkPosition(workPosition, user));
    }
}
